package com.hxzy.projectssmplus.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hxzy.projectssmplus.security.LoginUserDetails;
import com.hxzy.projectssmplus.security.TokenService;
import com.hxzy.projectssmplus.util.ServletUtil;
import com.hxzy.projectssmplus.vo.AjaxResult;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义退出处理类 返回成功 (注销)
 * 1)、从spring security中移出当前用户LoginUserDetails
 * 2)、从redis中删除uuid
 * 3)、向客户端输出 json串(成功，失败的)
 * 
 * @author admin
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        //根据uuid得到当前登录用户信息
        LoginUserDetails loginUser = tokenService.getLoginUserDetails(request);
        if (loginUser != null) {
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
        }
        AjaxResult ajaxResult = AjaxResult.success("退出成功");
        //向客户端输出json
        ServletUtil.outJson(response, ajaxResult);
    }

}
